package com.win.dao.impl;

import java.util.List;

import com.win.dao.IDeptDao;
import com.win.pojo.DeptInfo;
import com.win.util.DBHelper;

public class DeptDao implements IDeptDao{

	@Override
	public DeptInfo queryOne(Integer id) {
		String sql = "select * from dept_info where id = ?;";
		DeptInfo deptInfo = DBHelper.executeQueryToOne(sql, DeptInfo.class, id);		
		return deptInfo;
	}

	@Override
	public List<DeptInfo> query() {
		String sql = "select a.*,c.name as leaderName,count(*) as staffNum from dept_info as a \r\n" + 
				"left join staff_info as b on a.id = b.deptId \r\n" + 
				"left join staff_info as c on a.leaderId = c.id \r\n" + 
				"group by a.id";
		List<DeptInfo> list = DBHelper.executeQuery(sql, DeptInfo.class, null);
		return list;
	}

	@Override
	public Integer add(DeptInfo dt) {
		String sql = "insert into dept_info(deptName, leaderId)values(?,?)";
		Integer newDeptId = DBHelper.excuteInsert(sql, dt.getDeptName(), dt.getLeaderId());
		return newDeptId;
	}

	@Override
	public Integer update(DeptInfo dt) {
		if (!dt.hasValue()) {
			return -1;
		}
		StringBuffer sql = new StringBuffer("update dept_info set ");
		if (dt.getDeptName() != null) {
			sql.append("deptName = '" + dt.getDeptName()+"',");
		}
		if(dt.getLeaderId() != null) {
			sql.append("leaderId = '" + dt.getLeaderId()+"',");
		}
		sql = new StringBuffer(sql.substring(0, sql.length()-1));
		sql.append(" where id = " + dt.getId());
		Integer res = DBHelper.excuteUpdate(sql.toString(), null);
		return res;
	}

	@Override
	public Integer upLeaderForAdd(String leaderId) {
		String sql ="update dept_info set leaderId = null "
				+ "where id = (select deptId from staff_info where id = ?) and leaderId = ?";
		Integer res = DBHelper.excuteUpdate(sql, leaderId, leaderId);
		return res;
	}
	@Override
	public Integer del(String id) {
		String sql = "delete from dept_info where id = " +id;
		return DBHelper.excuteUpdate(sql, null);
	}


}
